package cn.edu.zafu.bigdata.XuShuXin.Exp1203;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: aluvfy
 * @description:  服务端，接受并回复消息
 * @date: 2024/12/3 9:58
 */
public class TCPServer_chat_xsx {
    public static void main(String[] args) throws IOException {
        int port = 12345;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is listening on port " + port);

        try {
            Socket clientSocket = serverSocket.accept();
            System.out.println("New client connected");

            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String inputLine;
            while ((inputLine = in.readLine()) != null) { // 读取客户端消息
                System.out.println("Client: " + inputLine); // 打印客户端消息
                System.out.println("请回复：");
                String serverInput = stdIn.readLine(); // 读取服务端用户的输入
                if (serverInput != null) {
                    out.println(serverInput); // 回复客户端
                }
            }
        } finally {
            serverSocket.close();
        }
    }
}
